package KK.Hunter.MapEdit.Logic
{
	import flash.geom.Point;

	public class LatticeLogic
	{
		protected var pixels:int;//正方形大小
		protected var width:int;//占格宽数量
		protected var height:int;//占格高数量
		
		
		private var point:Point;//返回格子
		
		private var diagonal:Number;
		
		private var offsetY:Number;
		public function LatticeLogic()
		{
			
			init();
		}
		private function init():void{
			point=new Point();
		}
		//返回点中的格子
		public function TouchIndex(mouseX:Number,mouseY:Number,OrgPos:Point):int{
			var result:int=0;
			OrgPos.y+=this.offsetY;
			var point:Point=touchLattice(mouseX,mouseY,OrgPos,this.diagonal,this.diagonal/2);
			result=(point.y+1)*height+point.x;
			return result;
		}
		//返回x 和 y
		public function TouchLattice(mouseX:Number,mouseY:Number,OrgPos:Point):Point{
			var result:Point;
			OrgPos.y+=this.offsetY;
			result=touchLattice(mouseX,mouseY,OrgPos,this.diagonal,this.diagonal/2);
			return result;
		}
		//设置45度的像速
		public function SetDiagonal(Diagonal:Number,width:int,height:int):void{
			var pixels:Number=Diagonal*Math.SQRT1_2*2;
			
			this.diagonal=Diagonal;
			SetRect(pixels,width,height);
		}
		//设置正方形
		public function SetRect(pixels:Number,width:int,height:int):void{
			this.diagonal=pixels/Math.SQRT1_2;
			this.pixels=pixels;
			this.width=width;
			this.height=height;
			
			this.offsetY=this.height*this.diagonal/4;
		}
		
		///////////////返回对应格子坐标//////////////////////////
		//   point  格子的位置
		//   OrgPos 偏移坐标
		///////////////////////////////////////////////////////
		public function GetPoint(point:Point,OrgPos:Point):Point{
			var result:Point=new Point();
			//计算坐标体系
			OrgPos.y+=this.offsetY;
//			point.x=this.width-point.x;
			
			result.x = (point.y + point.x) * this.diagonal/2 + OrgPos.x;
			result.y = (point.y - point.x) * this.diagonal/4 - this.diagonal/4 + OrgPos.y;
			return result;
		}
		
		
		
		//点击到的方块
		protected function touchLattice(mouseX:Number,mouseY:Number,OrgPos:Point,width:Number,height:Number):Point{
			var result:Point=point;
			var  fn:Number, fm:Number;        
			var nNIndex:int;
			var nMIndex:int;
			
			var mWidth:Number=(mouseX - OrgPos.x) / width;
			var nHeight:Number=(mouseY-OrgPos.y)/height;
			fn = mWidth - nHeight;    //OrgPos为图中的原点坐标
			fm = mWidth + nHeight;
			
			
			nNIndex=fn<0?int(fn)-1:int(fn);
			nMIndex=fm<0?int(fm)-1:int(fm); 
			
			nNIndex=this.height-nNIndex;
			//nMIndex=x-nMIndex;
			result.y=nNIndex;
			result.x=nMIndex;
			//mark!
			return result;
		}
		
		
		 
	}
}